package com.clouds.wms.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.clouds.wms.bean.Cmsmb;
import com.clouds.wms.bean.Cmsmg;
import com.clouds.wms.dao.CmsmbDao;
import com.clouds.wms.dao.CmsmgDao;
import com.clouds.wms.exception.DatabaseException;
import com.clouds.wms.exception.SysException;

@Service("cmsmbService")
public class CmsmbServiceImpl implements CmsmbService {

	@Resource(name="cmsmbDao")
	private CmsmbDao cmsmbDao;

	@Resource(name="cmsmgDao")
	private CmsmgDao cmsmgDao;

	@Override
	public Cmsmb getCmsmbByMbaa(String mbaa) throws SysException {
		return cmsmbDao.getCmsmbByMbaa(mbaa);
	}

	@Override
	public int getCmsmbCount(String mbaa, String mbab) throws SysException {
		return cmsmbDao.getCmsmbCount(mbaa, mbab);
	}

	@Override
	public List<Cmsmb> getCmsmbList(String mbaa, String mbab, int offset, int pageSize) throws SysException {
		return cmsmbDao.getCmsmbList(mbaa, mbab, offset, pageSize);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED, rollbackFor=DatabaseException.class)
	public int saveCmsmb(Cmsmb cmsmb, String meaas[]) throws SysException {
		List<Cmsmg> cmsmgList = new ArrayList<Cmsmg>();
		if(meaas != null && meaas.length > 0) {
			for(int i = 0; i < meaas.length; i++) {
				long meaa  = Long.parseLong(meaas[i]);
				if(meaa != 0){
					Cmsmg cmsmg = new Cmsmg();
					cmsmg.setMgab(cmsmb.getMbaa());
					cmsmg.setMgac(meaa);
					cmsmgList.add(cmsmg);
				}
			}
		}
		cmsmgDao.saveCmsmgs(cmsmgList);
		return cmsmbDao.saveCmsmb(cmsmb);
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED, rollbackFor=DatabaseException.class)
	public int updateCmsmb(Cmsmb cmsmb, String meaas[]) throws SysException {
		cmsmgDao.deleteCmsmgListByMbaa(cmsmb.getMbaa());
		List<Cmsmg> cmsmgList = new ArrayList<Cmsmg>();
		if(meaas != null && meaas.length > 0) {
			for(int i = 0; i < meaas.length; i++) {
				long meaa  = Long.parseLong(meaas[i]);
				if(meaa != 0){
					Cmsmg cmsmg = new Cmsmg();
					cmsmg.setMgab(cmsmb.getMbaa());
					cmsmg.setMgac(meaa);
					cmsmgList.add(cmsmg);
				}
			}
		}
		cmsmgDao.saveCmsmgs(cmsmgList);
		return cmsmbDao.updateCmsmb(cmsmb);
	}

	@Override
	public int deleteCmsmbByMbaa(String mbaa) throws SysException {
		return cmsmbDao.deleteCmsmbByMbaa(mbaa);
	}

	@Override
	public List<Cmsmb> getAllCmsmbList() throws SysException {
		return cmsmbDao.getAllCmsmbList();
	}

}
